export default {
	get: function(url, data, header) {
		return this.fun(url, "GET", data, header);
	},
	post: function(url, data, header) {
		return this.fun(url, "POST", data, header);
	},
	put: function(url, data, header) {
		return this.fun(url, "PUT", data, header);
	},
	delete: function(url, data, header) {
		return this.fun(url, "DELETE", data, header);
	},
	weixinUploadFile: function(url, path) {
		return this.weixinUploadFile(url, path);
	},
	arrayBufferToString: function(arr) {
		if (typeof arr === 'string') {
			return arr;
		}
		var dataview = new DataView(arr.data);
		var ints = new Uint8Array(arr.data.byteLength);
		for (var i = 0; i < ints.length; i++) {
			ints[i] = dataview.getUint8(i);
		}
		arr = ints;
		var str = '',
			_arr = arr;
		for (var i = 0; i < _arr.length; i++) {
			var one = _arr[i].toString(2),
				v = one.match(/^1+?(?=0)/);
			if (v && one.length == 8) {
				var bytesLength = v[0].length;
				var store = _arr[i].toString(2).slice(7 - bytesLength);
				for (var st = 1; st < bytesLength; st++) {
					if (_arr[st + i]) {
						store += _arr[st + i].toString(2).slice(2);
					}
				}
				str += String.fromCharCode(parseInt(store, 2));
				i += bytesLength - 1;
			} else {
				str += String.fromCharCode(_arr[i]);
			}
		}
		return str;
	},
	streamRequest(url, method, data, header, onChunkReceived) {
		data = data || {};
		header = header || {};
		header["Request-Type"] = "miniProgram";
		header["X-CURRENT-OPEN-ID"] = uni.getStorageSync('openId')
		const accountInfo = uni.getAccountInfoSync();
		header['WX-MA-APP-ID'] = accountInfo.miniProgram.appId;
		uni.showNavigationBarLoading();
		return new Promise((resolve, reject) => {
			// 创建请求任务
			  const requestTask = uni.request({
			    url: url,
			    method: method,
			    data: data,
			    enableChunked: true,  // 开启分块传输
				responseType: "arraybuffer",
				header: header,
			    success: (res) => {
					resolve(res)
			    },
			    fail: (err) => {
			      reject(er)
			    }
			  });
			  let chunkCache = new Uint8Array(0);
			  requestTask.onChunkReceived((res) => {
				  console.log(new DataView(res.data))
				  const arrayBuffer = res.data;
				    const uint8Array = new Uint8Array(arrayBuffer);
				    let data = uni.arrayBufferToBase64(uint8Array);
				    data = new Buffer(data, 'base64').toString('utf-8');
				    console.log(this.arrayBufferToString(res));
					onChunkReceived(this.arrayBufferToString(res));
				  // console.log(this.testDecode(new Uint8Array(res.data)))
				  // console.log(new TextDecoder("UTF-8").decode(new Uint8Array(res.data)))
				  // console.log(Array.from(new Uint8Array(res.data)).map(b => b.toString(16)));
				//   const uint8Array = new Uint8Array(res.data);
				//   let hex = Array.from(new Uint8Array(res.data))
    // .map(byte => byte.toString(16).padStart(2, '0'))
    // .join('')
				//   console.log("isChineseHex1", /(e[4-9a-f]|f[0-7])[0-9a-f]{4}/i.test(hex))
				//   hex = hex.replace(/%[^0-9a-f]{2}/gi, '')
				//   hex = hex.replace(/^0x/, '')
				//   hex = hex.replace(/%/g, '%25')
				//   const bytes = new Uint8Array(
				//       hex.match(/.{2}/g).map(h => parseInt(h, 16))
				//     );
				//   console.log("result1", new TextDecoder('utf-8').decode(bytes))
				  //   const text = new TextDecoder('utf-8').decode(uint8Array);
				  //   console.log(text);
				  // console.log("result2", this.isChineseInGBK(new Uint8Array(res.data)))
				//   const hexStr = Array.from(new Uint8Array(res.data))
				//       .map(b => b.toString(16).padStart(2, '0')).join('')
				// const utf8Pattern = /[e-f][0-9a-f]{2}[8-b][0-9a-f][8-b][0-9a-f]/i;
				//   // 检测GBK两字节模式（如"d6d0"对应"中"）
				//   const gbkPattern = /(8[1-9a-f]|9[0-9a-f]|[a-f][0-9a-f])[4-9a-f][0-9a-f]/i;
				//   console.log("result1", utf8Pattern.test(hexStr) || gbkPattern.test(hexStr));
			 //  console.log([...new Uint8Array(res.data)].map(x=>x.toString(16)));
			 //    const temp = new Uint8Array(chunkCache.length + res.data.byteLength);
			 //    temp.set(chunkCache, 0);
			 //    temp.set(new Uint8Array(res.data), chunkCache.length);
			 //    chunkCache = temp;
				// console.log("chunkCache", chunkCache)
				// const base64Str = wx.arrayBufferToBase64(res.data);
				//   const text = decodeURIComponent(escape(atob(base64Str)));
				//   console.log("text", text);
			  });
			  // // 监听分块数据接收
			  // requestTask.onChunkReceived(async (res) => {
			  //   try {
					// const blob = new Blob([res.data], {type: 'text/plain;charset=utf-8'});
					// const text = await blob.text();
					// console.log("text", text)
					// // const arrayBuffer = res.data; // 示例：包含中文的二进制数据
					// // const uint8Array = new Uint8Array(arrayBuffer);
					// // // 模拟写入GBK编码的中文"你好"
					// // // uint8Array.set(arrayBuffer, 0); 
					
					// // // 使用iconv-lite转换编码
					// // const text = iconv.decode(Buffer.from(uint8Array), 'win1252');
					// // console.log(text);
					
					// // const decoder = new TextDecoder('utf-8');
					// // const data = Buffer.from(res.data);
					// // let charset = chardet.detect(data);
					// // console.log("charset", charset)
					// // // const chunk = new TextDecoder("gbk").decode(res.data)
					// // console.log("chunk4", data.toString('win1252'))
					// // console.log(iconv.decode(data, 'win1252'))
					// // const newData = new Uint8Array(data);
					// // console.log("data1", newData)
					// //   const buffer = Buffer.from(newData);
					// //   console.log(decoder.decode(newData, {stream: true}));
					// // // 使用 TextDecoder 解码，注意设置 stream: true
					// // const chunk = decoder.decode(data, {stream: true});
					// // console.log("chunk", chunk)
					// // let data2 = chunk.replace("data:", "")
					// // console.log("data2", data2)
					// // buffer += chunk;
					
					// // // 处理可能的分块不完整问题
					// // const lines = buffer.split('\n');
					// // buffer = lines.pop() || ''; // 剩余不完整数据
					
					// // lines.forEach(line => {
					// //   if (line.trim()) {
					// // 	console.log('接收到的数据:', line);
					// // 	// 在这里处理你的业务逻辑
					// // 	console.log(line, line.data, JSON.parse(line.data))
					// //   }
					// // });
			  //  //    // 解码 ArrayBuffer 数据
			  //  //    const chunk = new TextDecoder('utf-8').decode(res.data, {stream: true});
			  //  //    console.log("chunk", chunk);
				 //  // onChunkReceived && onChunkReceived(chunk);
			  //   } catch (e) {
			  //     console.error('分块数据处理失败:', e);
			  //   }
			  // });
		})
		
		
		//#ifdef APP
		console.log("app端用plus.net API实现流式输出, 未测试过")
		//#endif
		//#ifdef H5
		console.log("h5端用fetch API实现流式输出，参考PC端scrm_html项目")
		//#endif
	},
	fun(url, method, data, header) {
		// let wechatAuditFlag = store.state.wechatAuditFlag;
		// console.log('wechatAuditFlag' + wechatAuditFlag)
		// let currentUserId = uni.getStorageSync('CURRENT_USER_ID')
		// if (wechatAuditFlag === 'false' && !currentUserId) {
		// 	return this.wechatLogin(url, method, data, header)
		// } else {
		// 	return this.request(url, method, data, header)
		// }
		return this.request(url, method, data, header)
	},
	request(url, method, data, header) {
		data = data || {};
		header = header || {};
		header["Request-Type"] = "miniProgram";
		header["X-CURRENT-OPEN-ID"] = uni.getStorageSync('openId')
		const accountInfo = uni.getAccountInfoSync();
		header['WX-MA-APP-ID'] = accountInfo.miniProgram.appId;
		uni.showNavigationBarLoading();
		let promise = new Promise(function(resolve, reject) {
			uni.request({
				url: url,
				header: header,
				data: data,
				method: method,
				success: function(res) {
					// if (typeof res.data === "object") {
					// 	// console.log(res.data,"接口调用返回")
					// 	if (res.data.code) {
					// 		if (res.data.code === -200) {
					// 			uni.showToast({
					// 				title: "为确保能向您提供最准确的服务，请退出应用重新授权",
					// 				icon: "none"
					// 			});
					// 			reject("请重新登录");
					// 		} else if (res.data.code === 401) {
					// 			uni.showToast({
					// 				title: res.data.message,
					// 				icon: "none"
					// 			});
					// 			setTimeout(function() {
					// 			}, 1000);
					// 			reject(res.data.msg);
					// 		}
					// 	}
					// }
					resolve(res);
				},
				fail: reject,
				complete: function() {
					uni.hideNavigationBarLoading();
				}
			});
		});
		return promise;
	},
	//上传文件，包含图片以外的文件
	weixinUploadFile(url, path) {
		let promise = new Promise(function(resolve, reject) {
			let _this = this
			wx.getFileSystemManager().readFile({
				filePath: path, //选择图片返回的相对路径
				encoding: 'base64', //编码格式
				success: res2 => { //成功的回调
					uni.showLoading({
						title: '加载中'
					});
					let end = path.substring(path.lastIndexOf('.') + 1)
					let header = {};
					header["Request-Type"] = "miniProgram";
					header["X-CURRENT-OPEN-ID"] = uni.getStorageSync('openId')
					uni.request({
						url: url,
						method: 'POST',
						data: {
							base64Code: 'data:image/' + end + ';base64,' + res2.data
						},
						header: header,
						success: function(res) {
							uni.hideLoading();
							//成功回调
							if (res.statusCode == 200) {
								let data = res.data
								if (data) {
									if (typeof data === "string") {
										data = JSON.parse(data)
									}
									if (data.code) {
										if (data.code === -200) {
											uni.showToast({
												title: "为确保能向您提供最准确的服务，请退出应用重新授权",
												icon: "none"
											});
											reject("请重新登录");
										} else if (data.code === 401) {
											uni.showToast({
												title: data.message,
												icon: "none"
											});
											setTimeout(function() {
											}, 1000);
											reject(data.msg);
										}
									}
								}
								resolve(data)
							}
							reject(res.data.msg);
						},
						fail:function(error){
							console.log("upload fail")
						}
					})
				}
			})
		})
		return promise;
	},
	wechatLogin(url, method, data, header) {
		return new Promise((resolve, reject) => {
			// 获取微信code
			this.getWechatCode().then(res => {
				// 依据code获取微信用户id
				this.getWxUserIdByCode(res).then(res => {
					// 依据微信用户Id获取用户信息
					this.getUserByWxUserId(res).then(res => {
						// 有数据证明为老用户，获取用户信息后继续使用
						if (res) {
							this.request(url, method, data, header).then(res => {
								resolve(res)
							}).catch(err => {
								reject(err)
							})
						} else {
							// 没用户信息，证明是新用户， 跳转到获取权限页面
						}
					}).catch(err => {
						uni.showToast({
							title: '操作失败，请稍后重试',
							icon: 'none',
							duration: 3000
						});
					})
				}).catch(err => {
					uni.showToast({
						title: '操作失败，请稍后重试',
						icon: 'none',
						duration: 3000
					});
				})
			}).catch(err => {
				uni.showToast({
					title: '操作失败，请稍后重试',
					icon: 'none',
					duration: 3000
				});
			})
		})
	},
	/**
	 * 获取微信code
	 */
	getWechatCode() {
		return new Promise((resolve, reject) => {
			uni.login({
				provider: 'weixin',
				success: function(loginRes) {
					let code = loginRes.code;
					resolve(code)
				},
				fail: (res) => {
					reject()
				}
			});
		})
	},
	/**
	 * 设置缓存信息
	 */
	setLocalStorageInfo(userCompanyInfo) {
		uni.showLoading({
			title: '正在加载'
		})
		uni.setStorageSync('USER_NAME', userCompanyInfo.name)
		uni.setStorageSync('USER_TEL', userCompanyInfo.user.mobile)
		uni.setStorageSync('USER_TYPE', userCompanyInfo.type)
		uni.setStorageSync('USER_TEL', userCompanyInfo.user.mobile)
		if (userCompanyInfo.isManager) {
			uni.setStorageSync('USER_MANAGER', 1)
		} else {
			uni.setStorageSync('USER_MANAGER', 0)
		}
		if (userCompanyInfo.company) {
			uni.setStorageSync('SCRM_COMPANY', userCompanyInfo.company)
			uni.setStorageSync('CURRENT_COMPANY_ID', userCompanyInfo.company.id)
		}
		if (userCompanyInfo.user) {
			uni.setStorageSync('SCRM_USER', userCompanyInfo.user)
			uni.setStorageSync('CURRENT_USER_ID', userCompanyInfo.user.id)
			let scrmUserId = uni.getStorageSync('CURRENT_USER_ID');
			this.scrmUserId = scrmUserId
		}
		uni.setStorageSync('SCRM_USER_COMPANY', userCompanyInfo)
		uni.hideLoading()
	},
	//上传文件，包含图片以外的文件
	uploadFile(url, path, header) {
		header = header || {};
		header["Request-Type"] = "miniProgram";
		header["X-CURRENT-OPEN-ID"] = uni.getStorageSync('openId')
		let promise = new Promise(function(resolve, reject) {
			uni.uploadFile({
				url: url,
				filePath: path,
				header: header,
				name: 'file',
				success: (res) => {
					if (res.statusCode == 200) {
						let data = res.data
						if (data) {
							if (typeof data === "string") {
								data = JSON.parse(data)
							}
							if (data.code) {
								// if (data.code === -200) {
								// 	uni.showToast({
								// 		title: "为确保能向您提供最准确的服务，请退出应用重新授权",
								// 		icon: "none"
								// 	});
								// 	reject("请重新登录");
								// } else if (data.code === 401) {
								// 	uni.showToast({
								// 		title: data.message,
								// 		icon: "none"
								// 	});
								// 	setTimeout(function() {
								// 		uni.reLaunch({
								// 			url: "/pages/main/login"
								// 		});
								// 	}, 1000);
								// 	reject(data.msg);
								// }
							}
						}
						resolve(data)
					}
					reject(res.data.msg);
				},
				fail: reject,
				complete: function() {
					uni.hideNavigationBarLoading();
				}
			});
		})
		return promise;
	}
};
